package com.openxt.nbzj.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class StringUtil {
    public static boolean isNull(Object obj) {
        return (obj == null || "".equals(obj.toString().trim())
                || "null".equals(obj.toString().trim())
                || "undefined".equals(obj.toString().trim()));
    }

    public static String getValue(Object obj) {
        return (isNull(obj) ? "" : obj.toString());
    }

    public static String formatDataSize(long size) {
        String ret = null;
        if (size < (1024 * 1024)) {
            ret = String.format("%dK", size / 1024);
        } else {
            ret = String.format("%.1fM", size / (1024 * 1024.0));
        }
        return ret;
    }

    public static String join(JSONArray array, String split) {
        if (array == null || array.isEmpty())
            return null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0, j = array.size(); i < j; i++) {
            sb.append(array.get(i)).append(split);
        }
        int i;
        if ((i = sb.lastIndexOf(split)) != -1)
            sb.deleteCharAt(i);
        return sb.toString();
    }

    public static String join(JSONArray array) {
        return join(array, ",");
    }

    public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONObject joResult = JSON.parseObject(json);
            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0, j = words.size(); i < j; i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }

    public static String doubleToLString(String d) {
        try {
            return String.valueOf(Double.valueOf(d).longValue());
        } catch (Exception e) {
            return d;
        }
    }
}
